from flask import Flask,request,session,redirect
from .view import account
from .view import order
from .view import task
from .view import user
from .task import updateTask
import config
from flask_apscheduler import APScheduler
from apscheduler.schedulers.background import BackgroundScheduler
from flask import Blueprint,render_template,request,redirect,session
from demo1.utils import DbConfigUtils
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.interval import IntervalTrigger
import importlib


def auth():
    if request.path.startswith("/static"):
        return
    if request.path=='/login':
        # 继续向后执行 不拦截
        return
    user_info=session.get('user_info')
    if  user_info:
        return
    return redirect('/login')

def create_app():
    app=Flask(__name__)
    app.secret_key='1234ddsadasdsds56'
    #  注册蓝图
    app.register_blueprint(account.ac)
    app.register_blueprint(order.od)
    app.register_blueprint(task.task)
    app.register_blueprint(user.us)
    app.register_blueprint(updateTask.reload_bp)
    app.before_request(auth)
    # 配置执行器
    app.config['SCHEDULER_EXECUTORS'] = {'default': {'type': 'threadpool', 'max_workers': 10}}
    # 配置作业存储器
    app.config['SCHEDULER_JOBSTORES'] = {'default': {'type': 'memory'}}
    app.config.from_object(config.Config)
    # 创建APScheduler对象，调度器是BackgroundScheduler
    scheduler = APScheduler(scheduler=BackgroundScheduler(daemon=True))
    scheduler.init_app(app)
    scheduler.start()
    with app.app_context():
        # 再重新加载
        load_jobs_from_db(scheduler)
        # 将 scheduler 存储在 app 的扩展字典中
    app.extensions['scheduler'] = scheduler
    return  app


# scheduler_loader.py


def load_jobs_from_db(scheduler):
    result = DbConfigUtils.fetchAll("SELECT * FROM scheduled_jobs WHERE enabled = TRUE")
    for row in result:
        job_id = row['id']
        func_name = row['func_name']
        trigger_type = row['trigger_type']

        # 动态导入函数
        module_name, func_name = func_name.rsplit('.', 1)
        module = importlib.import_module(module_name)
        func = getattr(module, func_name)

        # 构建触发器
        if trigger_type == 'cron':
            trigger = CronTrigger(
                hour=row['hour'],
                minute=row['minute'],
                second=row['second'],
                day_of_week=row['day_of_week']
            )
        elif trigger_type == 'interval':
            trigger = IntervalTrigger(seconds=int(row['second']))
        else:
            continue  # 跳过不支持的触发器类型

        # 添加任务
        scheduler.add_job(func=func, trigger=trigger, id=job_id, replace_existing=True)






